package com.bf.xpdd.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtility
{

	/**
	 * 计算两个日期的天数
	 * 
	 * @param d1
	 *            第一个日期
	 * @param d2
	 *            第二个日期
	 * @return |d1-d3|的天数差
	 */
	public static int getDaysBetween(Calendar d1, Calendar d2)
	{
		// 判断两个日期那个比较晚
		if (d1.after(d2))
		{
			java.util.Calendar swap = d1;
			d1 = d2;
			d2 = swap;
		}

		int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
		int y2 = d2.get(Calendar.YEAR);
		if (d1.get(Calendar.YEAR) != y2)
		{
			d1 = (Calendar) d1.clone();
			do
			{
				days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);// 得到当年的实际天数
				d1.add(Calendar.YEAR, 1);
			}
			while (d1.get(Calendar.YEAR) != y2);
		}
		return days;
	}

	/**
	 * 计算两个日期的天数差
	 * @param startday
	 * @param endday
	 * @return
	 */
	public static int getIntervalDays(Date startday, Date endday)
	{
		if (startday.after(endday))
		{
			Date cal = startday;
			startday = endday;
			endday = cal;
		}
		long sl = startday.getTime();
		long el = endday.getTime();
		long ei = el - sl;
		return (int) (ei / (1000 * 60 * 60 * 24));
	}
	
	
	/**
	 * 判断是否闰年
	 */
	public static boolean isLeapYear()
	{
		java.util.Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		{
			return true;
		}
		return false;
	}
	
	/**
	 * 获取当月天数
	 */
	public static int getMaxDayOfMonth()
	{
		Calendar calendar = Calendar.getInstance();
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 判断日期为当月第几天
	 */
	public static int getDayOfMonth(Date date)
	{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date beginTime = sdf.parse("2010-05-32 10:10:10");
		Date endTime = new Date();
		
		int d = getIntervalDays(beginTime, endTime);
		System.out.println(d);
		System.out.println(isLeapYear());
		System.out.println(getDayOfMonth(beginTime));
	}

}
